package com.playcrab.adouban;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.R.color;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.AdapterContextMenuInfo;

import com.google.gdata.client.douban.DoubanService;
import com.google.gdata.data.HtmlTextConstruct;
import com.google.gdata.data.Link;
import com.google.gdata.data.Person;
import com.google.gdata.data.PlainTextConstruct;
import com.google.gdata.data.TextContent;
import com.google.gdata.data.douban.MiniblogEntry;
import com.google.gdata.data.douban.MiniblogFeed;
import com.google.gdata.util.ServiceException;
import com.playcrab.adouban.util.DateTimeUtil;

/**
 * @author kevinye
 */
public class MiniblogList extends BaseActivity {
	private static final String LOG_TAG = "MiniblogList";
	int currentStartIndex = 1;
	private static int maxResults = 15;
	MiniblogListAdapter miniblgListAdapter = null;
	private Handler handler = new Handler();
	EditText editText = null;
	Button buttonMore = null;
	List<MiniblogEntry> miniblogs;


	public List<MiniblogEntry> getMiniblogs() {
		return miniblogs;
	}

	public void setMiniblogs(List<MiniblogEntry> miniblogs) {
		this.miniblogs = miniblogs;
	}

	private static final int MENU_SEARCH = Menu.FIRST + 1;
	private static final int MENU_SCAN = Menu.FIRST + 2; 

	public static final int MENU_REPLY = Menu.FIRST + 7;
	public static final int MENU_DELETE = Menu.FIRST + 8;
	private static final int MENU_VIEW_AUTHOR = Menu.FIRST + 100;
	private static final int MENU_VIEW_SUBJECT = Menu.FIRST + 101; 
	private static final int MENU_VIEW_USER = Menu.FIRST + 102; 
	
	private static final int MENU_VIEW_URL = Menu.FIRST + 105; 

	
	

	private static final int MENU_EXIT = Menu.FIRST + 12;
	private static final int MENU_REFRESH = Menu.FIRST + 106; 
	
	
	

	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// 显示列表
		setContentView(R.layout.miniblog_list);
		final ListView listView = (ListView) findViewById(R.id.miniblog_list);

		registerForContextMenu(listView);
		
		miniblgListAdapter = new MiniblogListAdapter(MiniblogList.this, new ArrayList<MiniblogEntry>());
		listView.setAdapter(miniblgListAdapter);

//		final ProgressDialog progressDialog = ProgressDialog.show(MiniblogList.this, MiniblogList.this.getResources().getText(R.string.waiting),
//				MiniblogList.this.getResources().getText(R.string.searching), true);
//		
//		new Thread() {
//			public void run() { 
//				miniblogs = updateMiniblogs();
//				handler.post(new Runnable() {
//					public void run() {
//						miniblgListAdapter = new MiniblogListAdapter(MiniblogList.this, miniblogs);
//						listView.setAdapter(miniblgListAdapter);
//						progressDialog.dismiss();
//					}
//				}); 
//
//			}
//		}.start();
  
		// render edit box
		editText = (EditText) findViewById(R.id.miniblog_edit);
		OnClickListener listener = new OnClickListener() {
			public void onClick(View v) {
				setTitle(MiniblogList.this.getResources().getText(R.string.sending ));
				DoubanService myService = getAuthedDoubanService();
				if(myService == null){
					return;
				}
				try {
					miniblgListAdapter.addMiniblog(myService
							.createSaying(new PlainTextConstruct((editText
									.getText()).toString())));
				} catch (IOException e) {
					setTitle("sending error");
					e.printStackTrace();
				} catch (ServiceException e) {
					setTitle("sending error");
					e.printStackTrace();
				}
			}
		};
		Button button = (Button) findViewById(R.id.miniblog_send_button);
		button.setOnClickListener(listener);

		InsertPanel();
	}
	
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenu.ContextMenuInfo menuInfo) {
		menu.setHeaderTitle("操作菜单");
		AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
		MiniblogEntry miniblog = this.miniblgListAdapter.itemList.get(info.position);
		
		
		//related links
 	    String content = ((HtmlTextConstruct)( (TextContent) miniblog.getContent()).getContent() ).getHtml();
 	    Pattern p = Pattern.compile("<a href=[\'\"]?(http:\\/\\/([a-z]+)\\.douban\\.com\\/([a-z]+)\\/([0-9a-zA-Z_]+))\\/?[\'\"]?>(.*)</a>", Pattern.DOTALL); 
	 	  Matcher m = p.matcher(content);
	      if (m.find()) {
	    	 String a= m.group(0);
	    	 final String b= m.group(1);//url
	    	 final String c= m.group(2);//type:movie,www,book,music...
	    	 String d= m.group(3);//subject,people
	    	 final String e= m.group(4);//id
	    	 String f= m.group(5);//title
	    	 if(d.equals("subject")){
	    		MenuItem item =  menu.add(0, MENU_VIEW_SUBJECT, 0, f);
	    		item.setOnMenuItemClickListener(new OnMenuItemClickListener(){

					@Override
					public boolean onMenuItemClick(MenuItem i) {
						Intent intent = new Intent(MiniblogList.this, ViewSubject.getViewClass(c));
						intent.putExtra("id", e );
						intent.putExtra("type", c );
						startActivity(intent);  
						return false;
					}
	    			
	    		});
	    		 
	    	 } else if(d.equals("people")){
	    		 MenuItem item =  menu.add(0, MENU_VIEW_USER, 0, f);
		    		item.setOnMenuItemClickListener(new OnMenuItemClickListener(){

						@Override
						public boolean onMenuItemClick(MenuItem i) {
							MiniblogList.this.viewUser(e);
							return false;
						}
		    			
		    		});	
	    	 
	    	 }	 
	    	 else{
	    	 
	    		 MenuItem item =  menu.add(0, MENU_VIEW_SUBJECT, 0, f);
		    		item.setOnMenuItemClickListener(new OnMenuItemClickListener(){

						@Override
						public boolean onMenuItemClick(MenuItem i) {
							MiniblogList.this.openWebBrowser(b); 
							return false;
						}
		    			
		    		});
		    		 
		    	  
		      }
	    	 
	    	 
	      }//end of if 
	      
	    //author
			final Person author = miniblog.getAuthors().get(0);
			
			MenuItem itemAuthor =  menu.add(0, MENU_VIEW_USER, 0, author.getName()  );
			itemAuthor.setOnMenuItemClickListener(new OnMenuItemClickListener(){ 
				@Override
				public boolean onMenuItemClick(MenuItem i) {  
					String sid = author.getUri().substring(author.getUri().lastIndexOf('/')+1); 
					MiniblogList.this.viewUser(sid);
					return false;
				}
				
			});
			
		 
		

	}
	
	
    @Override 
    public boolean onContextItemSelected(MenuItem item) {
    	
        AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
		MiniblogEntry se = this.miniblgListAdapter.itemList.get(info.position);
		String id = se.getId().substring(se.getId().lastIndexOf('/')+1); 
        switch (item.getItemId()) {
			

        }
		return super.onOptionsItemSelected(item);
        
    }
    
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
			case MENU_SEARCH: {
				Intent intent = new Intent(MiniblogList.this, Main.class);
				startActivity(intent);
				return true;
			}
			case MENU_REFRESH: {
				this.refreshMiniblogs();
				return true;
			}
			case MENU_SCAN:{
				Intent intent = new Intent(MiniblogList.this, Main.class);
				intent.putExtra("event", "scan" );
				startActivity(intent);
				return true;
			}
			 case MENU_EXIT: { 
	                finish();
	                return true;
	            }
				

		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		menu.add(0, MENU_REFRESH, 0, "刷新").setIcon(android.R.drawable.ic_menu_rotate)
		.setAlphabeticShortcut('R');  
		menu.add(0, MENU_EXIT, 0, "退出").setIcon(android.R.drawable.ic_menu_close_clear_cancel)
		.setAlphabeticShortcut('X'); 
		return true;
	}
	
	


	/*** returns miniblogs using current startIndex and increases startIndex ***/
	private List<MiniblogEntry> updateMiniblogs() {
		int currentStartIndex = 1;
		if(this.miniblgListAdapter == null || this.miniblgListAdapter.itemList == null)
			currentStartIndex = 1;
		else
			currentStartIndex = this.miniblgListAdapter.itemList.size()+1;
		
		return updateMiniblogs(currentStartIndex);
	}
	
	public void refreshMiniblogs(){
		if (this.miniblgListAdapter == null
				|| this.miniblgListAdapter.itemList == null)
			return ;
		Toast.makeText(
				getApplicationContext(),
				this.getResources().getText(
						R.string.waiting),
				Toast.LENGTH_SHORT).show();
 
		new Thread() {
			public void run() { 
				miniblogs = updateMiniblogs(1);  
				MiniblogList.this.miniblgListAdapter.itemList.clear();
				MiniblogList.this.miniblgListAdapter.itemList.addAll(miniblogs); 
				handler.post(new Runnable() {
					public void run() {
						MiniblogList.this.miniblgListAdapter.notifyDataSetChanged();
					}
				});
			 
			}
		}.start(); 
		 
	}
	
	private List<MiniblogEntry> updateMiniblogs(int startIndex) {
		currentStartIndex = startIndex; 
		String userId = getStoredUserId();
		MiniblogFeed mf;
		try {
			DoubanService myService = getAuthedDoubanService();
			if(myService == null){
				return new ArrayList();
			}
			mf = myService.getContactsMiniblogs(userId, currentStartIndex,
					maxResults);
			return mf.getEntries();

		} catch (ServiceException e) {
			e.printStackTrace();
			MiniblogList.this.showInfo(getString(R.string.service_error));
		}catch(IOException e) { 
			e.printStackTrace(); 
			MiniblogList.this.showInfo(getString(R.string.network_error));
		} 
		return new ArrayList();
	}

	public class MiniblogListAdapter extends AutoRefreshAdapter<MiniblogEntry> {

		private static final String LOG_TAG = "MiniblogListAdapter";
		Activity context;
		LayoutInflater inflater;
		WebView userIcon;
		TextView username, replyTo, updateBody, via, timestamp;
		List<MiniblogEntry> more_mblogs;

		public MiniblogListAdapter(Activity context, List<MiniblogEntry> miniblogList) {
			super(context, miniblogList);
			inflater = LayoutInflater.from(context);

			this.context = context;
			this.itemList = miniblogList;
			// TODO Auto-generated constructor stub
		}

		@Override
		public View getItemView(int position) {
			View row = inflater.inflate(R.layout.miniblog_row, null); 
			MiniblogEntry miniblog = itemList.get(position);  
			
			TextView content = (TextView) row.findViewById(R.id.miniblog_conent);
			content.setText((miniblog.getAuthors().get(0).getName()+" "+ ((TextContent) miniblog.getContent()).getContent() .getPlainText()) ); 
					 
			
			TextView published = (TextView) row.findViewById(R.id.miniblog_published);
			published.setText(DateTimeUtil.simpleFormat( miniblog.getPublished()));
			
			
			List<Link> images = miniblog.getLinks("image", null);
			if (images != null && images.size()>0) { 
				WebView miniblog_image = (WebView) row
				.findViewById(R.id.miniblog_image);
				miniblog_image.setLongClickable(false);
				miniblog_image.setClickable(false);
				miniblog_image.setBackgroundColor(color.transparent);
				String html_string = "<img src=\"" + images.get(0).getHref() + "\" align=\"right\"/>";
				miniblog_image.loadData(html_string, "text/html", "utf-8"); 
			}
//			row.setOnLongClickListener(new OnLongClickListener(){
//
//				@Override
//				public boolean onLongClick(View v) {
//					ContextMenu menu =
//					
//					// TODO Auto-generated method  
//					
//					return false;
//				}});
			return row;	 
		}

		/**
		 * @param miniblogEntry
		 */
		public void addMiniblog(MiniblogEntry miniblogEntry) {
			itemList.add(0, miniblogEntry);
			notifyDataSetChanged();
		}

		public void addMiniblogs(List<MiniblogEntry> newMiniblogs) {
			itemList.addAll(itemList.size(), newMiniblogs);
			notifyDataSetChanged();

		}
		
		protected boolean cacheInBackground() {
			more_mblogs = MiniblogList.this.updateMiniblogs();
			
			return(more_mblogs.size() == MiniblogList.maxResults);
		}
		
		protected void appendCachedData() {
			addMiniblogs(more_mblogs);
		}

	}
}